import java.net.*;
import java.io.*;

/** LocalTalk4.java
  LocalTalk4.java use the following features:
	1. Use InputStream's available() to test whether there are message from
	2. Use two threads for communication between the client and server.
client. 
*/

public class LocalTalk4 {

    public static void main(String args[] ) {
     int clientNum;
     if ( args.length < 1 )  clientNum = (int) (Math.random() * 100) + 1;
     else clientNum = Integer.parseInt(args[0]);
     try {
	Socket sk = new Socket("cmpsc5.cs.csubak.edu", 8900);
	ObjectOutputStream out = new ObjectOutputStream(sk.getOutputStream());
	InputStream       inStm = sk.getInputStream();
	ObjectInputStream in = new ObjectInputStream( inStm );

	String message;
	int mnum = 1;
	int len;
	while ( true ) {
		if ( inStm.available() > 0 ) {
			message = (String) in.readObject();
			System.out.println("Message Received by Client: " + message);
		}

		message = "Message " + mnum++ + " from client " + clientNum;
		out.writeObject(message);
		out.flush();

		Thread.sleep((int) ( Math.random() * 1000) + 100 );
	}
     } catch ( Exception e ) { e.printStackTrace(); }
   }
}
